package chess;

import java.util.ArrayList;
import java.util.Random;

import game.ChessGame;
import game.Game;

public class BadAIChessPlayer extends AIPlayer {

	private Random randomizer;
	
	public BadAIChessPlayer(String name,Game game, String colour) {
		super(name, game, colour);
		randomizer=new Random();
	}

	public void takeTurn(){
		ArrayList<Tile> movementTiles=null,attackTiles=null;
		chess.Tile dest=null;
		game.ChessGame curGame= (game.ChessGame)this.getGame();
		command.Command newMove;
		boolean goodPiece = false;
		chess.Piece pieceChosen = null;
		
		while (!goodPiece){
			
			pieceChosen = this.getMyPieces().get(randomizer.nextInt(getMyPieces().size())); //Choose a random piece

			while (pieceChosen.isDead()){
				pieceChosen = this.getMyPieces().get(randomizer.nextInt(getMyPieces().size())); //Choose a random piece until you get one that
																							//isn't dead.
			}
		
			movementTiles=pieceChosen.getMovementTiles();
		
			attackTiles=curGame.findAttackMoves(movementTiles,this);
			curGame.addSpecialChessMoves(pieceChosen.getCurrentTile(),this,movementTiles,attackTiles); //Should go here, after attackTiles, and before bad moves are filtered
			curGame.filterBadMoves(pieceChosen.getCurrentTile(),this,movementTiles,attackTiles); //Filter out things that would put you in
																					 //check!
		
			//If you can attack, choose a random attack
			if (attackTiles.size()!=0){
				dest = attackTiles.get(randomizer.nextInt(attackTiles.size()));
				goodPiece=true;
			}
			else if (movementTiles.size()!=0){  //Move to a random spot
				dest = movementTiles.get(randomizer.nextInt(movementTiles.size()));
				goodPiece=true;
			}
		}
		//Actually move the piece if it was a move
		if (movementTiles.contains(dest)){
			newMove = new command.MoveCommand(pieceChosen.getCurrentTile(),dest);	
		}
		else{ //Do the attack if it was an attack
			if (dest.isPieceHere()){
				newMove = new command.AttackCommand(pieceChosen.getCurrentTile(),dest,this);
			}
			else{
				// En passant attack
				newMove = new command.EnPassantAttackCommand(pieceChosen.getCurrentTile(),dest,this);
			}
			
		}
		
		newMove.execute();  //Execute the command
		
		curGame.listOfMoves.add(newMove); //Add this command to the list of moves made
		
		//Check to see if the move was a castle
		if (pieceChosen instanceof KingPiece){
				if ((dest.getX()==ChessGame.CASTLE_COLUMN_1)||(dest.getX()==ChessGame.CASTLE_COLUMN_2)){
					if(!newMove.hadMovedPreviously()){
						curGame.finishCastleMove(this,dest);//Castle
					}
				}
		}
		
		//Check if it is a pawn in the last row, if so, queen it
		if (pieceChosen instanceof PawnPiece){
			if (dest.getY() == ChessGame.BLACK_ROW || dest.getY()== ChessGame.WHITE_ROW){
				curGame.queenMe(dest,this);
			}
		}

		
	}
	
}
